use crate::{
    animate::Animator,
    ui::game_map::GameMapSettings,
    ui_class::{
        despawn_screen, enter_top_brand, game_panel, map_editor_text, menu_text_style,
        player1_text, player2_text, root_class, tank_selector,
    },
    widget::{sprite, sprite_children_a, sprite_root, sprite_sheet_a, text2d},
    GameState, OnExitClean,
};
use bevy::prelude::*;

pub struct MenuPlugin;
#[derive(Component)]
pub struct TankSelector(usize);

impl Plugin for MenuPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(OnEnter(GameState::Menu), setup_menu)
            .add_systems(Update, add_event.run_if(in_state(GameState::Menu)))
            .add_systems(OnExit(GameState::Menu), despawn_screen::<OnExitClean>);
    }
}

fn setup_menu(
    mut commands: Commands,
    mut window: Query<&mut Window>,
    mut settings: ResMut<GameMapSettings>,
) {
    let window = window.single_mut();
    settings.physics_center = Vec2::new(window.width() / 2., window.height() / 2.);
    commands.spawn(Camera2dBundle::default());
    sprite_root(root_class, commands, OnExitClean, |gc| {
        sprite_children_a(game_panel, gc, (), |gc| {
            sprite(enter_top_brand, gc, ());
            text2d("player1", (player1_text, menu_text_style), gc, ());
            text2d("player2", (player2_text, menu_text_style), gc, ());
            text2d("map editor", (map_editor_text, menu_text_style), gc, ());
            sprite_sheet_a(tank_selector, gc, TankSelector(0));
        });
    });
}

fn add_event(
    mut query: Query<(&mut Animator, &mut TankSelector)>,
    keyboard_input: Res<ButtonInput<KeyCode>>,
    mut state: ResMut<NextState<GameState>>,
) {
    for (mut animator, mut selector) in query.iter_mut() {
        if animator.get_pause() {
            if keyboard_input.pressed(KeyCode::ArrowUp) || keyboard_input.pressed(KeyCode::KeyW) {
                selector.0 = (selector.0 + 2) % 3;
                if selector.0 == 2 {
                    animator.exec_index(3);
                } else {
                    animator.exec_index(0);
                }
            } else if keyboard_input.pressed(KeyCode::ArrowDown)
                || keyboard_input.pressed(KeyCode::KeyS)
            {
                selector.0 = (selector.0 + 1) % 3;
                if selector.0 == 0 {
                    animator.exec_index(2);
                } else {
                    animator.exec_index(1);
                }
            }
            if keyboard_input.pressed(KeyCode::Enter) {
                match selector.0 {
                    0 => state.set(GameState::GameEnter),
                    1 => state.set(GameState::GameEnter),
                    2 => state.set(GameState::MapEditor),
                    _ => {}
                }
            }
        }
    }
}
